<?php

// +---------------------------------------------+
// |     Copyright  2010 - 2018 InterPhoto       |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+


include('includes/InterPhoto.Core.php');

CheckAccess('allowupload');

$action = ForceIncomingString('action', 'uploadform');


$smarty = new InterPhoto;

$allcategories = array();

@set_time_limit(900);

// ############################## FUNCTIONS #############################

function CreateDirectory($path) {
	if (!file_exists($path)) {
		mkdir($path, 0777);
		@chmod($path, 0777);
	}
}

function UploadImage($imagefile, $uploaddir, $file_path, $imagename) {
	CreateDirectory($uploaddir.$file_path);
	CreateDirectory($uploaddir.$file_path.'/32x32/');
	CreateDirectory($uploaddir.$file_path.'/80x80/');
	CreateDirectory($uploaddir.$file_path.'/160x160/');
	CreateDirectory($uploaddir.$file_path.'/760x760/');
	CreateDirectory($uploaddir.$file_path.'/original/');

	if((function_exists('move_uploaded_file') AND @move_uploaded_file($imagefile['tmp_name'], $uploaddir.$file_path.'/'.$imagename)) OR @rename($imagefile['tmp_name'], $uploaddir.$file_path.'/'.$imagename))	{

		$image_size = @getimagesize($uploaddir.$file_path.'/'.$imagename);
		if(!$image_size) return false;

		if ($image_size[0] > 760 || $image_size[1] > 760) {
			if (@rename($uploaddir.$file_path.'/'.$imagename, $uploaddir.$file_path.'/original/'.$imagename)) {
				CreateImageFile($uploaddir.$file_path.'/original/'.$imagename, $uploaddir.$file_path."/760x760/".$imagename,'760');
				CreateImageFile($uploaddir.$file_path.'/760x760/'.$imagename, $uploaddir.$file_path."/160x160/".$imagename,'160');
				CreateImageFile($uploaddir.$file_path.'/160x160/'.$imagename, $uploaddir.$file_path."/80x80/".$imagename,'80');
				CreateImageFile($uploaddir.$file_path.'/80x80/'.$imagename, $uploaddir.$file_path."/32x32/".$imagename,'32');
			}
		}else{
			if (@rename($uploaddir.$file_path.'/'.$imagename, $uploaddir.$file_path.'/760x760/'.$imagename)) {
				CreateImageFile($uploaddir.$file_path.'/760x760/'.$imagename, $uploaddir.$file_path."/160x160/".$imagename,'160');
				CreateImageFile($uploaddir.$file_path.'/160x160/'.$imagename, $uploaddir.$file_path."/80x80/".$imagename,'80');
				CreateImageFile($uploaddir.$file_path.'/80x80/'.$imagename, $uploaddir.$file_path."/32x32/".$imagename,'32');
			}
		}

		return true;

	}else{
		return false;
	}
}

function CreateImageFile($src_path, $des_path, $new_dims) {
	$source = @imagecreatefromjpeg($src_path);

	if ($source) {
		$imageX = @imagesx($source);
		$imageY = @imagesy($source);
		
		if ($imageX >= $imageY) {
			if($imageX >= $new_dims){
				$thumbX = $new_dims;
				$thumbY = (int)(($thumbX*$imageY) / $imageX );
			}else{
				$thumbX = $imageX;
				$thumbY = $imageY;
			}
		} else {
			if($imageY >= $new_dims){
				$thumbY = $new_dims;
				$thumbX = (int)(($thumbY*$imageX) / $imageY );
			}else{
				$thumbX = $imageX;
				$thumbY = $imageY;
			}
		}

		$dest_thum  = @imagecreatetruecolor($thumbX, $thumbY);
		@imagecopyresampled ($dest_thum, $source, 0, 0, 0, 0, $thumbX, $thumbY, $imageX, $imageY);
		@imageinterlace($dest_thum);
		@imagejpeg($dest_thum,$des_path,85);
		@ImageDestroy($dest_thum);
		@ImageDestroy($source);
	}
}

function GetCategorySelect($selectname, $selectedid = 0){
	$sReturn = '<select name="' . $selectname . '">';
	$sReturn .= GetOptions($selectedid);
	$sReturn .= '</select>';

	return $sReturn;
}

function GetOptions($selectedid = 0, $parentid = 0, $sublevelmarker = ''){
	global $icategories;

	if($parentid) $sublevelmarker .= '&minus;&minus;';

	$allicategories = $icategories;
	foreach($allicategories as $value){
		if($parentid == $value['parentid']){
			$sReturn .= '<option value="' . $value['categoryid'] . '" ' . Iif($selectedid == $value['categoryid'], 'SELECTED', '') . '>' . $sublevelmarker . $value['title'] . '</option>';

			$sReturn .= GetOptions($selectedid, $value['categoryid'], $sublevelmarker);
		}
	}

	return $sReturn;
}


if($action == 'insertimage' OR $action == 'updateimage')
{
	$imageid     = ForceIncomingInt('imageid');
	$categoryid     = ForceIncomingInt('categoryid');
	$actived     = ForceIncomingInt('actived');
	$title        = ForceIncomingString('title');
	$description        = ForceIncomingString('description');
	$keywords        = ForceIncomingString('keywords');
	$url        = ForceIncomingString('url');
	$sale     = ForceIncomingInt('sale');
	$price        = ForceIncomingString('price');
	$path        = ForceIncomingString('path');
	$filename        = ForceIncomingString('filename');

	if(strlen($title) == 0){
		$errors[] = $sys_langs['please_enter'].$langs['image'].$langs['title'];
	}

	if ($action == 'insertimage')
	{
		$imagefile         = $_FILES['imagefile'];

		$valid_image_types = array('image/pjpeg',	'image/jpeg', 'image/jpg');

		$uploaddir = BASEPATH.'MyWebsiteImages/';
		@chmod($uploaddir,0777);

		if (!$categoryid)
		{
			$errors[] = $sys_langs['nocategory'];
		}

		if (!function_exists('imagecreatetruecolor'))
		{
			$errors[] = $sys_langs['notsupportgd2'];
		}

		if (!is_dir($uploaddir)){
			$errors[] = $sys_langs['nodirectory'];
		}else if (!is_writable($uploaddir)){
			$errors[] = $sys_langs['notwritable'];
		}

		if($imagefile['size'] == 0)	{
			$errors[] = $sys_langs['errfilesize1'].ini_get('upload_max_filesize');
		}elseif (!IsUploadedFile($imagefile['tmp_name']) || !($imagefile['tmp_name'] != 'none' && $imagefile['tmp_name'] && $imagefile['name']) ){
			$errors[] ='Possible file upload attack!';
		}elseif(!in_array($imagefile['type'], $valid_image_types)){
			$errors[] = $sys_langs['invalidtype'];
		}else{
			$filesizelimit = $DB->query_first("SELECT title, datasize, watermark FROM " . TABLE_PREFIX . "categories WHERE categoryid = '$categoryid' ");
			if($imagefile['size'] > $filesizelimit['datasize'] *1024){
				$errors[] = str_replace('//1', $filesizelimit['title'], $sys_langs['errfilesize2']). DisplayFilesize($filesizelimit['datasize'] *1024);
			}else{
				$watermark = $filesizelimit['watermark'];
			}
		}

		if(!isset($errors))
		{
			$file_path_name = DisplayDate(time(), 'Y_m');
			$filepieces = explode('.', basename($imagefile['name']));
			$fileExtension = strtolower($filepieces[count($filepieces)-1]);
			$imagename = md5(uniqid(COOKIE_KEY.time())).'.'.$fileExtension;
			$file_path = $file_path_name.'_'.WEBSITE_KEY;

			if(UploadImage($imagefile, $uploaddir, $file_path, $imagename)){

				$DB->query("INSERT INTO " . TABLE_PREFIX . "images VALUES (NULL, 0,  '$categoryid', '$userinfo[userid]', '$userinfo[username]', '$userinfo[allowuploadshow]', '$watermark', '$sale', '0', 'all', '$file_path_name', '$imagename', '$price', '$title', '$description', '', '$keywords', '$url', '0', '0', '".time()."')");

				$thisimageid = $DB->insert_id();
				$DB->query("UPDATE " . TABLE_PREFIX . "images SET ordernum = '$thisimageid' WHERE imageid = '$thisimageid'");

				header("Location: ".GetUrl('mydesk.images.php'));
				exit();

			}else{
				$errors = $sys_langs['uploadfailed'];
			}
		}
	}elseif($action == 'updateimage' AND $imageid){
		if(!isset($errors))
		{
			$DB->query("UPDATE " . TABLE_PREFIX . "images SET 
			categoryid = '$categoryid',
			sale     = '$sale',
			price     = '$price',
			title     = '$title',
			description     = '$description',
			keywords     = '$keywords',
			url     = '$url'
			WHERE userid='$userinfo[userid]' AND imageid   = '$imageid'");

			$success = $sys_langs['savefinished'];
			$action = 'uploadform';
		}

	}
	  
	if(isset($errors))	{
		$errortitle = Iif($imageid, $langs['edit'], $langs['publish']).$langs['image'].$sys_langs['error'];
		$action = 'uploadform';
	}
}


if($action == 'uploadform')
{
	$getcategories = $DB->query("SELECT categoryid, parentid, title  FROM " . TABLE_PREFIX . "categories WHERE actived = 1 ORDER BY ordernum");
	$icategories = $DB->getrows($getcategories);

	$imageid = ForceIncomingInt('imageid');

	if(isset($errors))
	{
		$image = array('imageid'   => $imageid,
			'categoryid'     => $categoryid,
			'title'     => $title,
			'description'     => $_POST['description'],
			'keywords'     => $keywords,
			'url'     => $url,
			'sale'     => $sale,
			'actived'     => $actived,
			'path'     => $path,
			'filename'     => $filename,
			'price'     => $price);

	} else if($imageid) {
		$image = $DB->query_first("SELECT imageid, categoryid, actived, path, filename, title, description, keywords, url, sale, price FROM " . TABLE_PREFIX . "images WHERE imageid = '$imageid' AND userid='$userinfo[userid]' ");

		if(!isset($image)){
			CheckAccess();
		}
	}else{
		$image = array('imageid' => 0, 'categoryid' => 0);
	}

	$Editor = '<script src="'.BASEURL.'library/editor/nicEdit.js" type="text/javascript"></script>
	<script type="text/javascript">
	bkLib.onDomLoaded(function() {
	new nicEditor({fullPanel:true, iconsPath: \''.BASEURL.'library/editor/nicEditorIcons.gif\', maxHeight:170}).panelInstance("description658");
	});
	</script>';
	$smarty->assign('Editor', $Editor);
	$smarty->assign('categoryselect', GetCategorySelect('categoryid', $image['categoryid']));
	$smarty->assign('image', $image);
}


//Always needing
$pagenav = '<a href="'.GetUrl('index.php').'">'.$langs['home'].'</a> '.$langs['nav'].' <a href="'.GetUrl('mydesk.php').'">'.$langs['mydesk'].'</a> '.$langs['nav'].' <a href="'.GetUrl('mydesk.upload.php', '', '', '', Iif($image['imageid'], 'imageid='.$image['imageid'], '')).'">'.Iif($image['imageid'], $langs['edit'], $langs['publish']).$langs['image'].'</a>';
$smarty->assign('pagenav', $pagenav);
$smarty->assign('userinfo', $userinfo);
$smarty->assign('pagetitle', Iif($image['imageid'], $langs['edit'], $langs['publish']).$langs['image'] . ' - ' .$mainsettings['siteTitle']);

$smarty->interPlay('mydesk.upload.tpl');

?>